package com.lhh.adminlte.controller;

import com.lhh.adminlte.base.LTEUser;
import com.lhh.adminlte.base.TreeNode;
import com.lhh.adminlte.entity.Menu;
import com.lhh.adminlte.entity.MenuType;
import com.lhh.adminlte.entity.Role;
import com.lhh.adminlte.service.IMemberService;
import com.lhh.adminlte.service.IQRCodeService;
import com.lhh.adminlte.service.UserService;
import com.lhh.adminlte.util.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.util.*;

/**
 * @Auther: hanhui.liu
 * @Date: 2018/5/10 09:52
 * @Description:
 */
@Controller
@RequestMapping("s")
public class SystemController extends BaseController {

    @Autowired
    UserService userService;

    @Autowired
    IQRCodeService iqrCodeService;

    @Autowired
    IMemberService iMemberService;

    @RequestMapping("login")
    public String login() {
        return "/login";
    }

    @RequestMapping("check")
    public String check(@RequestParam("username") String userName, @RequestParam("password") String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(true);
        subject.login(token);
        if (subject.isAuthenticated()) {
            System.out.println("登录成功");
        }
        return "redirect:/s/index";
    }

    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/s/index";
    }

    @RequestMapping("error")
    public String error() {
        return "/error";
    }

    @RequestMapping("dashboard")
    public ModelAndView dashboard() throws ParseException {
        ModelAndView modelAndView = new ModelAndView();
        LTEUser user = getUser();
        long totalCode = iqrCodeService.countQrCode(null, null, null, null, null, null, null, null);
        long useCode = iqrCodeService.countQrCode(null, null, null, 2, null, null, null, null);
        Date startDate = DateUtil.formatDate(DateUtil.getSpecifiedDayBefore(new Date(), "yyyyMMdd"));
        Date endDate = DateUtil.formatDate(DateUtil.currentYYYYMMDD());
        long newCodeYestoday = iqrCodeService.countQrCode(null, null, null, null, null, startDate, endDate, null);
        long useCodeYestoday = iqrCodeService.countQrCode(null, null, null, 2, startDate, startDate, null, null);

        long totalMember = iMemberService.countMembers(null, null, null, null, null, null);
        long newMemberYestoday = iMemberService.countMembers(null, null, null, null, startDate, endDate);
        modelAndView.setViewName("/dashboard");
        modelAndView.addObject("totalCode", totalCode);
        modelAndView.addObject("newCodeYestoday", newCodeYestoday);
        modelAndView.addObject("useCode", useCode);
        modelAndView.addObject("useCodeYestoday", useCodeYestoday);
        modelAndView.addObject("totalMember", totalMember);
        modelAndView.addObject("newMemberYestoday", newMemberYestoday);
        return modelAndView;

    }

    @RequestMapping("index")
    public ModelAndView index(@RequestParam(value = "roleId", required = false) Integer roleId) {
        LTEUser user = getUser();
        List<Role> roles = userService.findRolesByUserId(user.getId());
        if (roles.size() > 0) {
            if (roleId == null) {
                Role role = roles.get(0);
                user.setCurrentRoleName(role.getName());
                user.setCurrentRoleId(role.getId());
            } else {
                for (Role role : roles) {
                    if (role.getId().equals(roleId)) {
                        user.setCurrentRoleName(role.getName());
                        user.setCurrentRoleId(role.getId());
                        break;
                    }
                }
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        if (user.getCurrentRoleId() != null) {
            List<Menu> menus = userService.findMenusByRoleId(user.getCurrentRoleId(), MenuType.SHOW);
            List<TreeNode> treeNodes = formatMenu(menus);
            modelAndView.setViewName("/index");
            modelAndView.addObject("roles", roles);
            modelAndView.addObject("user", user);
            modelAndView.addObject("menus", treeNodes);
        } else {
            //TODO：返回无角色信息页面
            modelAndView.setViewName("/index");
        }
        return modelAndView;
    }

    /**
     * 格式化菜单成树结构
     *
     * @param menus
     * @return
     */
    public List<TreeNode> formatMenu(List<Menu> menus) {
        Set<Integer> parentIds = new HashSet<Integer>();
        Set<Integer> childIds = new HashSet<Integer>();
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getLevel() == null || menu.getLevel() == 0) {
                parentIds.add(menu.getId());
                TreeNode treeNode = new TreeNode();
                treeNode.setId(menu.getId());
                treeNode.setIcon(menu.getIcon());
                treeNode.setName(menu.getName());
                List<Menu> tempMenus = userService.findChildrenByParentId(menu.getId(), MenuType.SHOW);
                List<TreeNode.Child> children = new ArrayList<TreeNode.Child>();
                for (Menu tempMenu : tempMenus) {
                    childIds.add(tempMenu.getId());
                    TreeNode.Child child = treeNode.new Child();
                    child.setId(tempMenu.getId());
                    child.setIcon(tempMenu.getIcon());
                    child.setName(tempMenu.getName());
                    child.setUrl(tempMenu.getUrl());
                    children.add(child);
                }
                treeNode.setChildList(children);
                treeNodes.add(treeNode);
            } else {
                if (!childIds.contains(menu.getId())) {
                    if (parentIds.contains(menu.getParentId())) {
                        TreeNode currentTreeNode = null;
                        for (TreeNode treeNode : treeNodes) {
                            if (treeNode.getId() == menu.getParentId()) {
                                currentTreeNode = treeNode;
                                TreeNode.Child child = currentTreeNode.new Child();
                                child.setId(menu.getId());
                                child.setUrl(menu.getUrl());
                                child.setName(menu.getName());
                                child.setIcon(menu.getIcon());
                                currentTreeNode.getChildList().add(child);
                                break;
                            }
                        }
                    } else {
                        Menu parentMenu = userService.findParentByChidId(menu.getId(), MenuType.SHOW);
                        TreeNode treeNode = new TreeNode();
                        treeNode.setId(parentMenu.getId());
                        treeNode.setName(parentMenu.getName());
                        treeNode.setIcon(parentMenu.getIcon());
                        parentIds.add(parentMenu.getId());
                        childIds.add(menu.getId());
                        TreeNode.Child child = treeNode.new Child();
                        child.setId(menu.getId());
                        child.setIcon(menu.getIcon());
                        child.setName(menu.getName());
                        child.setUrl(menu.getUrl());
                        List<TreeNode.Child> children = new ArrayList<TreeNode.Child>();
                        children.add(child);
                        treeNode.setChildList(children);
                        treeNodes.add(treeNode);
                    }
                }
            }
        }
        return treeNodes;
    }

}
